package net.sourceforge.jsorter;

import java.lang.reflect.InvocationTargetException;

/**
 * 
 * @author Jason Rutherglen
 */
public class SortReflect {
	public static final int METHOD = 1;
	public static final int FIELD = 2;
	public int type;
	public String methodName;
	public String fieldName;
	public Object[] params;

	private SortReflect() {
	}
  
	public static class MethodException extends Exception {
		public MethodException(Throwable throwable) {
			super(throwable);
		}
	}
	
	public Object get(Object value) throws MethodException {
    if (type == METHOD) {
    	try {
        return MethodUtil.call(methodName, params, value);
    	} catch (InvocationTargetException invocationTargetException) {
    		throw new MethodException(invocationTargetException.getCause());
    	} catch (Exception exception) {
    		throw new MethodException(exception);
    	}
    } else if (type == FIELD) {
      return FieldUtil.getFieldValue(fieldName, value);
    }
    throw new RuntimeException("type is invalid");
  }

	public static SortReflect field(String fieldName) {
		SortReflect sortReflect = new SortReflect();
		sortReflect.type = FIELD;
		sortReflect.fieldName = fieldName;
		return sortReflect;
	}

	public static SortReflect method(String methodName) {
		SortReflect sortReflect = new SortReflect();
		sortReflect.type = METHOD;
		sortReflect.methodName = methodName;
		return sortReflect;
	}

	public static SortReflect method(String methodName, Object[] params) {
		SortReflect sortReflect = new SortReflect();
		sortReflect.type = METHOD;
		sortReflect.methodName = methodName;
		sortReflect.params = params;
		return sortReflect;
	}

}
